package com.xiaomi.back.controller;

import com.xiaomi.back.service.commoditys.CommoditysService;
import com.xiaomi.back.service.malltype.MallService;
import com.xiaomi.pojo.Malltype;
import com.xiaomi.util.ToolsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


@Controller
@PropertySource("classpath:config.properties")
public class UpCommFileController {

    @Value("${upload.path}")
    private String uploadPath ;

    @Autowired
    private CommoditysService commoditysService;

    @Autowired
    private MallService mallService;


    //跳转 添加商品页面
    @RequestMapping("/GoUpComm")
    public String GoUpComm(Model model){
        List<Malltype> malltypes=mallService.getMallType();
        model.addAttribute("malltypes",malltypes);
        return "back/Comm/UpCommFile";
    }

    //上传
    @RequestMapping("/UpFile")
    @ResponseBody
    public int UpFile(String comname, String miaoshu, int lx, Double price, String config, int count, MultipartFile files){
        int result=0;
        //先获取文件名称
        String fileName = files.getOriginalFilename() ;

        //修改文件名 新文件名+原文件后缀 xxxx.jpg
        String fileNewName = ToolsUtil.getFileNewName(fileName);
        System.out.println(fileNewName);
        File upFile = new File(uploadPath, fileNewName) ;

        //文件目录是否存在
        if(!upFile.exists()) {
            upFile.mkdirs() ;
        }

        try {
            files.transferTo(upFile);
            Boolean res=commoditysService.addCommInfo(lx,comname,miaoshu,price,config,count,fileNewName);
            if(res){
                result=1;
            }else{
                result=0;
            }

        } catch (IOException e) {
            result= 0;
            e.printStackTrace();
        }
        return result;


    }
}
